const { T_exam_label } = require('../models/t_exam_label')
const { T_exam_paper, T_exam_paper_to_question } = require('../models/t_exam_paper')
const { T_exam_question } = require('../models/t_exam_question')
const { T_exam_questions_and_label } = require('../models/t_exam_questions_and_label')
const { T_exam_target_to_question } = require('../models/t_exam_target_to_question')
const { T_exam_paper_info } = require('../models/t_exam_paper_info')
const { Op } = require('sequelize')
const { t_label_to_realLabel } = require('../models/T_label_to_realLabel')
const { T_exam_target } = require('../models/t_exam_target')
exports.autoProducePaper = async (req, res) => {
    //客户端发送需要自动成卷的id
    const id = req.query.id

    // function shuffleArray(array) {
    //     for (let i = array.length - 1; i > 0; i--) {
    //         const j = Math.floor(Math.random() * (i + 1));
    //         [array[i], array[j]] = [array[j], array[i]];
    //     }
    //     return array;
    // }

    function hasCommonElement(arr1, arr2) {
        return arr1.some(item => arr2.includes(item));
    }

    function randomSort() {
        return Math.random() - 0.5; // 生成 -0.5 到 0.5 之间的随机数
    }


    await T_exam_paper_to_question.destroy({
        where: {
            paper_id: id
        }
    })

    //找到这张试卷的基本信息
    const paperInfo = await T_exam_paper.findOne({
        where: {
            id: id
        },
        attributes: ['type_paper', 't_user_and_a_c_s_id']
    }
    )

    if (paperInfo === null) {
        return res.json({
            "code": 200,
            "mes": "没有找到该试卷"
        })
    }

    //把试卷的课程和试卷类型拿出来
    const ACSId = paperInfo.t_user_and_a_c_s_id
    const subId = paperInfo.subId
    const paperType = paperInfo.type_paper


    // const targetInfoQ = await T_exam_target_to_question.findAll({
    //     where: {
    //         paperType: paperType,
    //         subId: subId,
    //     },
    //     attributes:
    //         ['targetId', 'questionNum', 'questionType', 'score']
    // })


    // const labelInfo = await T_exam_label.findAll({

    //     where: {
    //         sub_id: subId
    //     },
    //     attributes: ['id', 'label']

    // })


    //找到这张自动生成试卷的题型顺序
    const paperOrderInfo = await T_exam_paper_info.findOne({
        where: {
            type: paperType,
            t_user_and_a_c_s_id: ACSId,
        },
        attributes: ['order'],
    })

    if (paperOrderInfo === null || paperOrderInfo.order === null) {
        return res.json({
            code: "200",
            mes: "未定义出题顺序"
        })
    }

    //将题型顺序的key封装为数组
    const Order = Object.keys(paperOrderInfo.order)
    const stringError = []
    //从题型出发开始遍历
    for (let j = 0; j < Order.length; j++) {
        const key = Order[j]
        const questionType = paperOrderInfo.order[key]
        console.log("题型是 = ", paperOrderInfo.order[key]);


        //通过题型查找有什么课程目标需要出这个题型
        const kindType = await T_exam_target_to_question.findAll({

            where: {
                paperType: paperType,
                t_user_and_a_c_s_id: ACSId,
                questionType: questionType
            },
            attributes: ['targetId', 'questionNum', 'score']
        })

        // console.log(kindType);
        //一个题目的容器
        let questionTank = []
        for (let h = 0; h < kindType.length; h++) {

            console.log('目标id', kindType[h].targetId);
            //找到这个课程目标的标签

            console.log("值为", kindType[h].targetId, "的targetID");
            const realLael = await t_label_to_realLabel.findAll({
                where: {
                    target_id: kindType[h].targetId
                },
                attributes: ['label_id']
            })

            const targetName = await T_exam_target.findOne({
                where: {
                    id: kindType[h].targetId
                },
                attributes: ['target_name']
            })

            const realLaelArray = realLael.map(item => item.label_id)
            console.log("筛选出来合适的标签有", realLaelArray);
            const TabelId = await T_exam_label.findAll({
                where: {
                    id: {
                        [Op.in]: realLaelArray
                    }
                },
                attributes: ['id']
            })

            // console.log('符合的TabelID', TabelId);

            const tableIdArray = TabelId.map(obj => obj.id)
            console.log('符合的TabelIDArray', tableIdArray);
            //找到这个课程目标的问题id
            const AllquestionId = await T_exam_questions_and_label.findAll({

                where: {
                    label_id: {
                        [Op.in]: tableIdArray
                    }
                },
                attributes: ['question_id'],
                group: ['question_id']
            })



            const allquestionIdArray = AllquestionId.map(obj => obj.question_id)
            console.log("以下是问题的id", allquestionIdArray)
            //通过题型和问题id确定题目
            //不仅是这个标签的又是这个题型的
            let questionContent = await T_exam_question.findAll({


                where: {
                    id: {
                        [Op.in]: allquestionIdArray
                    },
                    type: questionType

                },
                attributes: ['id']

            })




            const questionContentArray = questionContent.map(obj => obj.id)

            if (questionContentArray.length < kindType[h].questionNum) {
                stringError.push("符合" + targetName.target_name + "的" + paperOrderInfo.order[key] + "不足" + kindType[h].questionNum + "道")
            }
            console.log("以下是全部符合条件的问题id", questionContentArray);

            //打乱顺序
            // questionContentArray = shuffleArray(questionContentArray)
            questionContentArray.sort(randomSort)

            let arr = questionContentArray.splice(0, kindType[h].questionNum)
            console.log("符合条件的切片", arr);

            //检查题目的切片是否有相同题目
            let n = 0
            while (hasCommonElement(arr, questionTank)) {
                n++
                questionContentArray.sort(randomSort)

                arr = questionContentArray.splice(0, kindType[h].questionNum)
                if (n === 20) {
                    stringError.push("因为题目数量不够导致的题型冲突,该试卷出现重复题型")
                    break
                }
            }

            questionTank = questionTank.concat(arr)
            console.log("questionTank的内容为\n\n\n\n", questionTank);

            //结束课程目标循环，把这种题型的并且符合数目的对象装入questionTank
            //
        }

        // questionTank.sort(randomSort)
        console.log("洗牌后的题tank\n\n\n\n\n\n", questionTank);
        //批量插入对象数组封装
        const dataInsert = []
        for (let y = 0; y < questionTank.length; y++) {
            dataInsert.push({
                paper_id: id,
                question_id: questionTank[y],
                question_num: y
            })
        }


        //批量插入
        T_exam_paper_to_question.bulkCreate(dataInsert)
            .then(() => {
                console.log('批量插入成功');
            })
            .catch(err => {
                console.error('批量插入失败', err);
            });

        //结束一种题型的循环循环
    }
    res.json({
        "code": 200,
        "content": "自动生成试卷成功",
        "error": stringError
    })
}








